package com.myjava.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;


/***
 * 对接第三方接口有关的接口
 */
public class ExecuteUtils {

    private final static Log log = LogFactory.get();

    public static JsonElement execute(String url, List<NameValuePair> params) throws Exception {
        String content = executeStr(url, params);
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(content);
        if (jsonElement != null && !jsonElement.isJsonNull() && jsonElement.isJsonObject()) {
            String code = jsonElement.getAsJsonObject().get("code").getAsString();
            if (StrUtil.equalsIgnoreCase(code, "200")) {
                //请求成功
                JsonElement datas = jsonElement.getAsJsonObject().get("data");
                return datas;
            }
        }
        return null;
    }


    public static JsonElement executeGetPage(String url, List<NameValuePair> params) throws Exception {
        String content = executeStr(url, params);
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(content);
        if (jsonElement != null && !jsonElement.isJsonNull() && jsonElement.isJsonObject()) {
            String code = jsonElement.getAsJsonObject().get("code").getAsString();
            if (StrUtil.equalsIgnoreCase(code, "200")) {
                //请求成功
                JsonElement datas = jsonElement.getAsJsonObject().get("page");
                return datas;
            }
        }
        return null;
    }

    public static String executeStr(String url, List<NameValuePair> params) throws Exception {
        log.info("访问url:" + url);
        long currentTime = System.currentTimeMillis();
        log.info("当前时间：" + DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //设置请求响应时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(15000).setConnectionRequestTimeout(10000).setSocketTimeout(15000).build();
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        post.setEntity(new UrlEncodedFormEntity(params, Charsets.UTF_8));
        //设置请求响应时间
        CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(post);
        Integer code = closeableHttpResponse.getStatusLine().getStatusCode();
        log.info("response code:{}", code);
        if (code == HttpStatus.SC_OK) {
            String content = EntityUtils.toString(closeableHttpResponse.getEntity(), Charsets.UTF_8);
            log.info("response content:{}", content);
            log.info("消耗：" + (System.currentTimeMillis() - currentTime) + "毫秒");
            log.info("当前时间：" + DateTime.now().toString("yyyy-MM-dd HH:mm:ss"));
            return content;
        }
        return null;
    }

    public static JsonElement postJson(String url, JSONObject parms) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            //httpPost.setEntity(new StringEntity(JSON.toJSONString(parms), "utf-8"));
            httpPost.setHeader("Content-Type", "application/json");

            StringEntity entity = new StringEntity(parms.toString(), Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            //防止中文乱码，统一utf-8格式
            String body = EntityUtils.toString(response.getEntity(), "UTF-8");
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(body);
            if (jsonElement != null && !jsonElement.isJsonNull() && jsonElement.isJsonObject()) {
                String code = jsonElement.getAsJsonObject().get("code").getAsString();
                if (StrUtil.equalsIgnoreCase(code, "200")) {
                    //请求成功
                    JsonElement datas = jsonElement.getAsJsonObject().get("data");
                    return datas;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }
}
